//
//  MaskOfLayerViewController.m
//  CoreAnimation
//
//  Created by 张国文 on 16/10/9.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "MaskOfLayerViewController.h"

@interface MaskOfLayerViewController ()

@property (nonatomic, strong) UIImageView *peopleImageV;
@property (nonatomic, strong) CALayer *maskLayer; // 蒙版

@end

@implementation MaskOfLayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.peopleImageV = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 300, 400)];
    self.peopleImageV.image = [UIImage imageWithName:@"taylorswift"];
    [self.view addSubview:_peopleImageV];
    
    // 蒙版
    self.maskLayer = [[CALayer alloc] init];
    self.maskLayer.frame = CGRectMake(100, 20, 200, 200);
//    self.maskLayer.contents = (__bridge id _Nullable)([UIImage imageWithName:@"蒙版2"].CGImage);
    self.maskLayer.contents = (__bridge id _Nullable)([self getAnomalyShape].CGImage);
 //   self.maskLayer.backgroundColor = [UIColor redColor].CGColor; // 蒙版不可以设置背景颜色，否则蒙版失效
  // [self.view.layer addSublayer:_maskLayer];
     self.peopleImageV.layer.mask = self.maskLayer;
    
}

// 得到一个不规则图形
- (UIImage *)getAnomalyShape
{
    
    UIGraphicsBeginImageContext(CGSizeMake(200, 200));
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self.maskLayer renderInContext:ctx];
    CGContextSetLineWidth(ctx, 0);
    CGContextMoveToPoint(ctx, 0, 100);
    CGContextAddLineToPoint(ctx, 0, 200);
    CGContextAddLineToPoint(ctx, 200, 200);
    CGContextAddLineToPoint(ctx, 200, 100);
    // 画一个二次贝塞尔
    CGContextAddQuadCurveToPoint(ctx, 100, 0, 0, 100);
    CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor);
    CGContextFillPath(ctx); // 如果要得到蒙版的图形，必须用fill来得到实心图形
    UIImage *endImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return endImage;
}


@end
